package com.zstu.lvxiang.interceptor;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.zstu.lvxiang.config.AccessLimit;
import com.zstu.lvxiang.pojo.Student;
import com.zstu.lvxiang.service.IStudentService;
import com.zstu.lvxiang.utils.CookieUtils;
import com.zstu.lvxiang.vo.RespBean;
import com.zstu.lvxiang.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class AccessLimitInterceptor implements HandlerInterceptor {
    @Autowired
    IStudentService studentService;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            Student stu = getStu(request, response);
            HandlerMethod hm = (HandlerMethod) handler;
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if (accessLimit == null) {
                return true;
            }
            boolean needLogin = accessLimit.needLogin();
            if (needLogin) {
                if (stu == null) {
                    render(response, RespBeanEnum.SESSION_ERROR);
                    return false;
                }
                request.setAttribute("sno", stu.getSno());
            }
        }
        return true;
    }

    private void render(HttpServletResponse response, RespBeanEnum sessionError) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        RespBean respBean = RespBean.error(sessionError);
        out.write(new ObjectMapper().writeValueAsString(respBean));
        out.flush();
        out.close();
    }

    /*
        获取当前登录用户
     */
    private Student getStu(HttpServletRequest request, HttpServletResponse response) {
        String session = CookieUtils.getCookieValue(request, "sno");
        //        String session = request.getHeader("session");
        if (!StringUtils.hasText(session)) {
            return null;
        }
        return studentService.getStuByCookie(session, request, response);
    }
}
